/*
 * gridelementsk.js
 * 格点要素实况
 */
;
(function(call) {
	var main = {
		baseUrl: CafeJS.CXT,
		mapId: "tjMap",
		playList: null,
		datepicker: null,
		legendpicker: null,
		router: {
			getGridData: '/api37/shortWarn/sk/queryGridDataFormSK100m',
            queryNewestTimeFormSK100m:'http://10.226.107.37:8089/shortWarn/sk/queryNewestTimeFormSK100m',
			productcfg: "/business/common/json/product.json"
		},
		init: function() {
			this.getLatestTime();
			this.initView();
		},
		initView: function() {
			var that = this;
			that.initDatePicker();
			$.getJSON(that.router.productcfg, function(cfg){
				that.initProductList(cfg);
			})
		},
		// 初始化产品列表
		initProductList: function(cfg) {
			var that = this
			var params = {
				container: '.product-content.gridElementSk',
				data: cfg.gridElementSk,
				eleClick: function(ele, oldEle, selected) {
					var ptype = ele.type; //当前要素的类型
					var name = ele.ele_name;

					that.clearGridLayer();

					var pro = {
						name:  '格点要素实况_' + name,
						time: that.calcStartTime(ele),
						bussitype: 'gridElementSk',
						ele: ele,
						isGrid: true,
						isSK: true
					}
					if (selected) {
						$(".gridElementSk .product-list li.active").each(function(i, item) {
							if ($(item).data('eleid') != ele.ele_id) 
								$(item).click();
						})
						CafeJS.layerManage.removeLayer({ name: "格点要素实况_"+oldEle.ele_name }); // 删除上一个选中要素的图层

						// 增加产品图层
						that.addLayerManage(pro);
						that.queryEleData(ele, pro.time);
					} else {
						CafeJS.layerManage.removeLayer(pro); // 删除当前要素的图层
					}
				}
			};
			CafeJS.analysis(params);
		},
		// 初始化时间控件
		initDatePicker: function() {
			var _this =  this;
			this.datepicker = CafeJS.Datepicker({
				appendTo: "#datepicker-gridElementSk",
				curDate: _this.latestTime,
				type: 3,
				timeInterval: 15,
				autoPush: true,
				call: function(val) {
					_this.queryMultiEleData();
				}
			});
			$("#datepicker-gridElementSk").show();
		},
		// 初始化图例
		initLegentpicker: function(ele, appendTo) {
			var that = this;
			var layers = that.getModels(ele);
			var layerIds = [];
			$.each(layers,function(i,m){
				layerIds.push(m.id);
			});
			CafeJS.Legentpicker({
				appendTo: appendTo,
				gisId: that.mapId,
				layerId: layerIds,
				totalWidth : 400,
				h_legend: 15,
				seq : 'decrease',
				productId: ele.color_id,
				isShowSlider : false
			});
		},
		// 初始化播放列表
		initPlayList: function(pro){
			var that = this;
			var startTime = pro.time;

			var layers = this.getModels(pro.ele);
			var interval = pro.ele.interval || 5;
			this.playList = CafeJS.Timeline3({
				appendTo : "#a-m-timeline",
				curDate : startTime,
				type : 1,
				pro: pro,
				dateOpt: {
					dateFmt : 'yyyy-MM-dd hh:mm',
					timeInterval: interval,
					customHm: []
				},
				timeInterval: interval,
				layers: layers,
				gisId : that.mapId,
				call : function(pro){
					CafeJS.layerManage.updateLayer(pro);
					var ele = pro.ele;
					that.queryEleData(ele, pro.time);
				},
				getPlayData: function(pro, timeArr){}
			});
		},
		// 查询已选择要素
		queryMultiEleData: function() {
			var that = this;
			var pro, time;
			$(".gridElementSk .product-list li.active").each(function(i, ele){
				pro = $(ele).data('pro');
				time = that.calcStartTime(pro);
				CafeJS.layerManage.updateLayerTime(time, 'gridElementSk', null, pro.ele_id);
				that.queryEleData(pro, time);
			});
		},
		// 查询要素数据
		queryEleData: function(ele, time) {
			var that = this;
			var ptype = ele.type;
			that.queryGridData(ele, time)
		},
		// 最新实况时间
		getLatestTime: function () {
			var that = this;
			$.ajax({
				url: that.router.queryNewestTimeFormSK100m,
				type: 'GET',
				dataType: 'json',
				async: false
			}).done(function (res) {
				if (res.isSuccess && res.data&& res.data !="")
					that.latestTime = res.data.substring(0,4)+"-"+res.data.substring(4,6)+"-"+res.data.substring(6,8)+" "+res.data.substring(8,10)+":"+res.data.substring(10,12)+":00";
			})
		},
		// 数据
		queryGridData: function(ele, time){
			var that = this;
			var element = ele.ele_id;
			if (!element) return;

			if (time.indexOf(',') == -1) {
				time = new Date(time).format('yyyyMMddhhmmss');
			}
			loading.add();
			CafeJS.ajax({
                url: that.router.getGridData,
                params: {
                	element:element,
                	queryTime:time
                },
                type: "GET",
                success: function (e) {
                    loading.remove();
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(element);
                        return;
                    }
					debugger;
                    that.drawGridRawMap(arrayBuffer, ele);
                },
                error:function(){
                    loading.remove();
                    alert("查询数据失败");
                }
            })
		},
		// 绘制格点色斑图
		drawGridRawMap: function (data, ele) {
			var that = this;
			var typeArr = this.getModels(ele);
            var colorObj = CafeJS.Legentconfig().cfg()[ele.color_id] || {};
            if (ele.models == 'isoline') {
                gridUtil.createIsoline(data, typeArr[0].id, colorObj.levels, GLMap.geometryData.areaconfig.Haihe.rings);
            } else {
				// 显示色斑和数值
				colorObj.cutFlag = true;
				colorObj.areaCode = 'Haihe';
                GIS.GridShow.showGrid(this.mapId, typeArr, data, {}, colorObj);
			}
			var min = ele.type == 'TP'?0.1:null;
			//CafeJS.legentPicker.updateLegentRange(typeArr,that.mapId,min);
		},
		// 增加产品图层
		addLayerManage: function(pro) {
			var that =  this;
			if (CafeJS.layerManage) {
				CafeJS.layerManage.addLayer(pro);
			} else {
				CafeJS.layerManage = CafeJS.LayerManage({
					appendTo : "#c-b-layermanage",
					mapId: that.mapId,
					proInfo: pro,
					call: function(pro) {
						CafeJS[pro.bussitype].initPlayList(pro);
					},
					more: function(pro){
						CafeJS[pro.bussitype].stationView(pro);
					},
					close: function(pro) {
						CafeJS[pro.bussitype].delLayer(pro);
					}
				})
			}
			if (pro.isGrid && pro.ele.models != "isoline") {
				that.initLegentpicker(pro.ele, '.cafe-layer-item.active');
			}
		},
		// 根据时间间隔获取开始时间
		calcStartTime: function(ele) {
			var time = new Date(this.datepicker.getVal());
			return time.format('yyyy-MM-dd hh:mm');
		},
		// 删除图层后取消要素选择
		delLayer: function(pro) {
			var eleid = pro.ele.ele_id;
			$(".gridElementSk .product-list li.active").each(function(){
				if ($(this).data('eleid') == eleid){
					$(this).click();
					return false;
				}
			})
		},
		// 清除格点GIS图层
		clearGridLayer: function() {
			var layerIds = [];
			GLMap.layerIds.forEach(function(layerId){
				if (layerId.indexOf('gridElementSk-layer') != -1) {
					layerIds.push(layerId);
				}
			})
			GIS.LayerControll.deleteLayer(this.mapId, layerIds);
		},
		// 获取要素样式
		getModels: function(ele){
			var models = [];
			$.each(ele.models.split(","),function(i,m){
				var layerId = "gridElementSk-layer-"+ m + "-" + ele.ele_id;
				models.push({
					type : m,
					visible : true,
					id : layerId
				});
			});
			return models;
		}
	};
	if (typeof call === 'function') {
		CafeJS.gridElementSk = main;
		call(main);
	}

})(function(main) {
	CafeJS.models(['datepicker', 'legentpicker', 'legentconfig', 'ajax', 'timeLine3'], function() {
		main.init();
	});
});